package com.feeyo.monitor.service.imp;

import com.feeyo.monitor.enumeration.HttpContentType;
import com.feeyo.monitor.service.HttpService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author <a href="mailto:bliulei@variflight.com">liulei</a>
 * @Description Created by liulei on 2018/1/15 下午4:49.
 */
@Service
public class DefaultHttpService implements HttpService {
    Logger logger = LoggerFactory.getLogger(DefaultHttpService.class);
    private final OkHttpClient client = new OkHttpClient();

    @Override
    public int post(String url, HttpContentType contentType, Object data) {
        RequestBody requestBody = null;

        switch (contentType){
            case FORM:
                break;
            case JSON:
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                requestBody = RequestBody.create(JSON, (String)data);
                break;
            case TEXT:
                MediaType text = MediaType.parse("text/plain; charset=utf-8");
                requestBody = RequestBody.create(text,(String)data);
                break;
        }

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                //logger.info(response.body().string());
                return response.code();
            } else {
                //logger.error(response.body().string());
                return response.code();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
